package com.example.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.gateway.utils.SWUrlsUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wxy
 * @Date 2021/1/26 13:52
 * @Version 1.0
 */
@Component
public class OverallSituationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getPath().toString();
        Boolean bool = SWUrlsUtils.judgeSwaggerUrl(uri);
        if (bool) {
            return chain.filter(exchange);
        }
        List<String> heads = exchange.getRequest().getHeaders().get("UID");
        if (CollectionUtils.isEmpty(heads)) {
            ServerHttpResponse response = exchange.getResponse();
            Map<String, Object> map = new HashMap<>();
            map.put("code", -1);
            map.put("data", "网关验证权限错误，非法的参数头!");
            map.put("msg", "网关验证权限错误，非法的参数头!");
            byte[] bits = JSONObject.toJSONString(map).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.OK);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
